<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;

class RabbitmqSend extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'mq:send';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $connection = new AMQPStreamConnection(env('RABBITMQ_HOST'), env('RABBITMQ_PORT'), env('RABBITMQ_LOGIN'), env('RABBITMQ_PASSWORD'));
        $channel = $connection->channel();
//        $channel->queue_declare('hello1', false, false, false, false);
//
//        $msg = new AMQPMessage('Hello World!');
//        $channel->basic_publish($msg, '', 'hello');
        $channel->exchange_declare('logs', 'fanout', false, false, false);

        $data = '';
        if(empty($data)) $data = "info: Hello World!";
        $msg = new AMQPMessage($data);
        $channel->basic_publish($msg, '', 'hello');

        echo " [x] Sent 'Hello World!'\n";

        $channel->close();
        $connection->close();
//        /**
//         * 发送消息
//         */
//        $exchangeName = 'demo';
//        $routeKey = 'hello';
//        $message = 'Hello World!';
//        // 建立TCP连接
//        $connection = new \AMQPConnection([
//            'host' => env('RABBITMQ_HOST'),
//            'port' => env('RABBITMQ_PORT'),
//            'vhost' => env('RABBITMQ_VHOST'),
//            'login' => env('RABBITMQ_LOGIN'),
//            'password' => env('RABBITMQ_PASSWORD'),
//        ]);
//
//        $connection->connect() or die("Cannot connect to the broker!\n");
//
//        try {
//            $channel = new \AMQPChannel($connection);
//
//            $exchange = new \AMQPExchange($channel);
//            $exchange->setName($exchangeName);
//            $exchange->setType(AMQP_EX_TYPE_DIRECT);
//            $exchange->declareExchange();
//
//            echo 'Send Message: ' . $exchange->publish($message, $routeKey) . "\n";
//            echo "Message Is Sent: " . $message . "\n";
//        } catch (AMQPConnectionException $e) {
//            var_dump($e);
//        }
//
//// 断开连接
//        $connection->disconnect();
    }
}
